//
//  MJRefreshBackStateFooter.swift
//  OC-Swift
//
//  Created by 陆文宇 on 2017/2/15.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit

class MJRefreshBackStateFooter: MJRefreshBackFooter {
    
    var labelLeftInset: CGFloat!
    var isRefreshingTitleHidden: Bool = false
    lazy var stateTitles: Dictionary<MJRefreshState, String> = [:]
    lazy var stateLabel: UILabel = UILabel.mj_label()
    override var state: MJRefreshComponent.MJRefreshState {
        set {
            if super.state != newValue {
                super.state = newValue
            }
            
           stateLabel.text = stateTitles[newValue]
        }
        
        get {
            return _state
        }
    }
    override init(refreshingClosure: @escaping MJRefreshComponentRefreshingClosure) {
        super.init(refreshingClosure: refreshingClosure)
        
        addSubview(stateLabel)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setTitle(_ title: String, forState state: MJRefreshState) -> Void {
        stateTitles[state] = title
        stateLabel.text = stateTitles[self.state]
    }
    
    func titleForState(_ state: MJRefreshState) -> String {
        return stateTitles[state]!
    }
    
    @objc private func stateLabelClick() -> Void {
        if state == .idle {
            beginRefreshing()
        }
    }
    
    override func prepare() {
        super.prepare()
        
        labelLeftInset = MJRefreshLabelLeftInset
        
        setTitle(Bundle.mj_localizedString(for: MJRefreshBackFooterIdleText), forState: .idle)
        setTitle(Bundle.mj_localizedString(for: MJRefreshBackFooterPullingText), forState: .pulling)
        setTitle(Bundle.mj_localizedString(for: MJRefreshBackFooterRefreshingText), forState: .refreshing)
        setTitle(Bundle.mj_localizedString(for: MJRefreshBackFooterNoMoreDataText), forState: .noMoreData)
    }
    
    override func placeSubviews() {
        super.placeSubviews()
        
        if stateLabel.constraints.count != 0 {
            return
        }
        
        stateLabel.frame = bounds
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
